package com.yunchuang.controller.user;

import cn.hutool.core.util.StrUtil;
import com.wf.captcha.utils.CaptchaUtil;
import com.yunchuang.model.dto.UserRegisterDto;
import com.yunchuang.service.UserService;
import com.yunchuang.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户注册接口
 *
 * @author ItJiange
 * @date 2023/10/21
 */
@WebServlet("/user/register")
public class UserRegisterController extends HttpServlet {
    private final Logger logger= LoggerFactory.getLogger("logback");
    private final UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");
        String userEmail = req.getParameter("userEmail");
        String verCode = req.getParameter("verCode");
        // 2. 校验
        if (StrUtil.hasEmpty(username, password, verCode)) {
            logger.info("请求参数为空！请重新登录！");
            resp.sendRedirect("/login.html");
            return;
        }
        if (!password.equals(confirmPassword)) {
            logger.info("密码不一致！请重新注册！");
            resp.sendRedirect("/login.html");
            return;
        }
        if (!CaptchaUtil.ver(verCode, req)) {
            CaptchaUtil.clear(req);
            logger.info("验证码不正确！请重新注册！");
            resp.sendRedirect("/login.html");
            return;
        }

        // 封装为注册对象
        UserRegisterDto userRegisterDto = new UserRegisterDto();
        userRegisterDto.setUserName(username);
        userRegisterDto.setUserPassword(password);
        userRegisterDto.setEmail(userEmail);

        userService.userRegister(userRegisterDto);

        logger.info("注册成功！");
        resp.sendRedirect("/login.html");
    }
}
